#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2020/9/7 15:27
# @Author : wn 
# @File: caleandtime.py
# @SoftWare: PyCharm
# @Site:
# @Table:
# ｡◕‿◕｡｡◕‿◕｡｡◕‿◕｡

import csv
import json
import os

from django.http import HttpResponse
from django.shortcuts import render
from django.views import View

from Manager.utils.pageSearch import *
from Django_Admin import settings


class CaleAndTime(View):
    def get(self, request):
        # 当前在第几页
        off = request.GET.get('offset', None)
        # 一页几条
        lim = request.GET.get('limit', None)

        # get请求修改页面字段值
        get_ss_modify = request.GET.get('modify_ss', None)
        if lim is None and get_ss_modify is not None:
            ss_list = list(Tradetime.objects.filter(id=get_ss_modify))
            for item in ss_list:
                result_dict = {}
                result_dict['start_time'] = item.start_time  # str
                result_dict['stop_time'] = item.stop_time  # str
            return JsonResponse(result_dict, safe=False)

        if lim is None:
            html = "caleandtime.html"
            caleObj = Calendar.objects.all()
            cale_list = []
            tt_list = []
            for item in caleObj:
                cale_list.append(model_to_dict(item))
            ttObj = Tradetime.objects.all()

            for item in ttObj:
                tt_list.append({'id': [item.start_time, item.stop_time, item.pk]})
            content = {
                'caleObj': cale_list,
                'ttObj': tt_list,
                'url': '/strategy/caleandtime'
            }
            return render(request, html, content)

    def post(self, request):
        if request.POST.get('addORmodify_DB', None):
            tradingday = request.POST.get('data', None)
            try:
                if Calendar.objects.filter(tradingday=tradingday).exists():
                    Calendar.objects.filter(tradingday=tradingday).update(
                        tradingday=tradingday
                    )
                else:
                    Calendar.objects.create(
                        tradingday=tradingday
                    )
                return HttpResponse('y')
            except Exception as e:
                return HttpResponse(e)
        elif request.POST.get('del_DB', None):
            try:
                id = request.POST.get('id')
                if id != '':
                    # 单个删除之辈
                    Calendar.objects.filter(tradingday=id).delete()
                else:
                    # 全选之流
                    tradingdayList = json.loads(request.POST.get('tradingdayList'))
                    for tradingday in tradingdayList:
                        Calendar.objects.filter(tradingday=tradingday).delete()
                return HttpResponse('y')
            except Exception as e:
                return HttpResponse(e)
        elif request.POST.get('delTradeTime_DB', None):
            try:
                id = request.POST.get('id')
                if id != '':
                    # 单个删除之辈
                    Tradetime.objects.filter(pk=id).delete()
                else:
                    # 全选之流
                    ssList = json.loads(request.POST.get('tradingdayList'))
                    for ss in ssList:
                        Tradetime.objects.filter(pk=ss).delete()
                return HttpResponse('y')
            except Exception as e:
                return HttpResponse(e)
        elif request.POST.get('td_search', None):
            data = json.loads(request.POST.get('data'))
            tradingday = data.get('tradingday', None)
            caleObj = Calendar.objects.filter(tradingday__contains=tradingday)
            cale_list = []
            for item in caleObj:
                cale_list.append(model_to_dict(item))
            return JsonResponse(cale_list, safe=False)
        elif request.POST.get('addORmodifyTradeTime_DB', None):
            try:
                data = json.loads(request.POST.get('data'))
                start_time = data.get('start_time', None)
                stop_time = data.get('stop_time', None)
                id = data.get('id', None)
                if tuple([start_time]) in Tradetime.objects.values_list('start_time'):
                    return HttpResponse('r1')
                if tuple([stop_time]) in Tradetime.objects.values_list('stop_time'):
                    return HttpResponse('r2')
                # if Tradetime.objects.filter(start_time=start_time,stop_time=stop_time).exists():
                #     return HttpResponse('r1')
                if id:
                    Tradetime.objects.filter(pk=id).update(
                        start_time=start_time,
                        stop_time=stop_time
                    )
                else:
                    Tradetime.objects.create(
                        start_time=start_time,
                        stop_time=stop_time
                    )
                return HttpResponse('y')
            except Exception as e:
                print(e)
                return HttpResponse(e)
        elif request.POST.get('sstime_search', None):
            data = json.loads(request.POST.get('data'))
            start_time = data.get('start_time', None)
            stop_time = data.get('stop_time', None)
            ttObj = Tradetime.objects.all()
            if start_time:
                ttObj = Tradetime.objects.filter(start_time__contains=start_time)
            if stop_time:
                ttObj = ttObj.filter(stop_time__contains=stop_time)
            tt_list = []
            for item in ttObj:
                tt_list.append({'id': [item.start_time, item.stop_time, item.pk]})
            return JsonResponse(tt_list, safe=False)


def CaleAndTimeInput(request):
    try:
        # 1.文件上传，写入到服务端：
        textObj = request.FILES.get('txt_file', None)
        filePath = os.path.join(os.path.join(settings.MEDIA_ROOT),textObj.name)
        with open(filePath,'wb') as f:
            for chunk in textObj.chunks():
                f.write(chunk)
        # 2.文件上传，读取上传的内容，写入到数据库中，而非传统的根据model字段存入文件名
        cale_list = Calendar.objects.values_list()
        if os.path.exists(filePath):
            with open(filePath, 'r',encoding='utf-8') as f:
                reader = csv.reader(f)
                csv_list = []
                for row in reader:
                    if tuple([row[0]]) not in cale_list:
                        csv_list.append(Calendar(tradingday=row[0]))
                Calendar.objects.bulk_create(csv_list)
                return JsonResponse({'isSuccess':'ok'},safe=False)
        else:
            return JsonResponse({'isSuccess':'false','info':'tradingday.csv文件路径不存在，导入失败。'},safe=False)
    except Exception as e:
        print(e)
        return JsonResponse({"isSuccess":"error",'info':'请检查程序'})

